package com.example.demo.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.alibaba.fastjson2.JSONObject;
import com.example.demo.activity.PhoneActivity;

import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PhoneViewModel extends ViewModel {
    private static final String TAG = "PhoneViewModel";

    private String url = "https://api.jisuapi.com/shouji/query?appkey=f3557914adabf438&shouji=@number@";

    private MutableLiveData<PhoneInfo> data;

    public PhoneViewModel() {
        data = new MutableLiveData<>();
    }

    public LiveData<PhoneInfo> getUserLiveData() {
        return data;
    }


    public void loadData(String number){
        new Thread(() -> {
            try{

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder() .url(url.replace("@number@", number)) .build();
                Response response = client.newCall(request).execute();
                String body = response.body().string();
                Log.i(TAG, body);

                JSONObject mapObj = JSONObject.parseObject(body);
                JSONObject resultObj = mapObj.getJSONArray("result").getJSONObject(0);
                PhoneInfo info = new PhoneInfo();
                info.setNumber(number);
                info.setProvince(resultObj.getString("province"));
                info.setCity(resultObj.getString("city"));
                info.setCompany(resultObj.getString("company"));
                info.setCardtype(resultObj.getString("cardtype"));
                info.setAreacode(resultObj.getString("areacode"));

                data.postValue(info);

            }catch (Exception e){
                Log.i(TAG, Objects.requireNonNull(e.getMessage()));
            }
        }).start();
    }

}
